<?php

class PackageTypeAction extends Action {

	private $listMetricSystemUnitsStatement;
	private $getMetricSystemUnitNameStatement;
	private $getPackageTypeNameStatement;

	function __construct(){
		parent::__construct();
		$this->insertStatement = parent::prepareStatement("INSERT INTO packageunits (name, metric_system_unit_id, quantity) VALUES (?,?,?)");
		$this->listMetricSystemUnitsStatement = parent::prepareStatement("select metric_system_unit_id, name from metricsystemunits");
		$this->getMetricSystemUnitNameStatement = parent::prepareStatement("select name from metricsystemunits where metric_system_unit_id = ?");
	}
	
	function listMetricSystemUnits(){
		$this->listMetricSystemUnitsStatement->execute();
		$this->listMetricSystemUnitsStatement->bind_result($metric_system_unit_id, $name);

		$resultSet = array();
		while ($this->listMetricSystemUnitsStatement->fetch()) {
			array_push($resultSet, array($metric_system_unit_id, $name));
		}
		return $resultSet;
	}
	
	function getMetricSystemUnitName($metricSystemUnitId){
		$rc = $this->getMetricSystemUnitNameStatement->bind_param("i", $metricSystemUnitId);
		if ( false===$rc ) {
            printf('bind_param failed: %s', htmlspecialchars($this->getMetricSystemUnitNameStatement->error));
			die;
        }
		
		$this->getMetricSystemUnitNameStatement->execute();
		$this->getMetricSystemUnitNameStatement->bind_result($metricSystemUnitName);

		$resultSet = array();
		while ($this->getMetricSystemUnitNameStatement->fetch()) {
			array_push($resultSet, array($metricSystemUnitName));
		}
		if(sizeof($resultSet) > 1){
			throw new Exception("Multiple values found for metric system unit id (" . $metricSystemUnitId . ")");
		}
		return $resultSet[0][0];
	}
	
	function insert($packageUnitName, $metricSystemUnitId, $quantity){
		if(!$packageUnitName){
			throw new Exception('packageUnitName cannot be null.');
		}
		if(!$metricSystemUnitId){
			throw new Exception('metricSystemUnitId cannot be null.');
		}
		if(!$quantity){
			throw new Exception('quantity cannot be null.');
		}
		
		$rc = $this->insertStatement->bind_param("sid", $packageUnitName, $metricSystemUnitId, $quantity);
		if ( false===$rc ) {
            printf('bind_param failed: %s', htmlspecialchars($this->insertStatement->error));
			die;
        }
		
		$rc = $this->insertStatement->execute();
        if ( false===$rc ) {
                printf('execute failed: %s', htmlspecialchars($this->insertStatement->error));
                die;
        }
	}
}